import os
import shutil
import datetime
import requests
from tools.utils import load_config, loc_collection, loc_zq_collection
from upload.upload_future import update_future_to_mongo
from upload.upload_spot_price import upload_spot_stock_from_zhouqi
from cal_all import cal_six
from cal_all import find_history_and_upload_pred
from cal.cal_pred import upload_informer_pred


def async_now():
    resp = requests.post('http://192.168.1.153:30217/commodities/synchronize_data')
    status_code = resp.status_code
    print(status_code)


def clear_cache():
    dir_path = 'data/main_contract_cache'
    print('rm tree', dir_path)
    shutil.rmtree(dir_path)
    print('mkdirs', dir_path)
    os.makedirs(dir_path)


def auto_work(td='goods'):
    cfg = load_config()
    if td == 'goods':
        today = 'goods'
    else:
        today = str(datetime.date.today())
    coll = loc_zq_collection('to_it', today)
    coll.drop()  # 清除1.9数据库的所有数据
    clear_cache()  # 0、清除缓存的期货数据，否则更新期货数据就是旧的
    update_future_to_mongo()  # 1、更新期货数据

    for mode in ['现货', '库存']:  # 2、更新现货库存(从周琪建立的1.9数据库中提取）
        upload_spot_stock_from_zhouqi(mode)
    for mode_ in ['现货', '期货', '基差', '价差', '库存']:  # 3、计算 mode 数据并上库，依赖于第2步现货和库存数据是最新的
        record_d, record_l = cal_six(mode_, "tjd_category")
        coll.insert_many(record_l)

    find_history_and_upload_pred(coll, cfg, '日')  # 4、提取预测数据并上库，依赖于第三步完成.日度库保存在3.179 stock 中，按照日期排列
    # find_history_and_upload_pred(coll, cfg, '周')  # 4.2 周度数据需要再规划下怎么样更方便
    upload_informer_pred()


if __name__ == "__main__":
    auto_work('goods')
    async_now()  # 同步数据
